//
//  JKNewFeatureViewController.swift
//  JKWeibo
//
//  Created by albert on 16/5/15.
//  Copyright © 2016年 albert. All rights reserved.
//  新特性界面

import UIKit
import SnapKit

class JKNewFeatureViewController: UIViewController {
    
    /** 新特性界面的个数 */
    private var maxCount: Int = 4
    /** cell重用ID */
    private let newFeatureCellID = "newFeatureCell"
    
    /** 新特性图片数据 */
    private lazy var imageNames: [String] = {
        var names: [String] = []
        
        for i in 0..<self.maxCount{
            //new_feature_1
            names.append("new_feature_\(i + 1)")
        }
        
        return names
    }()
    /** 分页小点 */
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBAction func passBtnClick(){
        // 发出切换到主页的通知
        NSNotificationCenter.defaultCenter().postNotificationName(JKSwitchRootViewControllerNotification, object: nil, userInfo: [JKSwitchRootViewControllerKey : JKSwitchToMainValue])
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化分页小点
        setupPageControl()
    }
    
    //MARK: - 初始化分页小点
    private func setupPageControl(){
        pageControl.numberOfPages = maxCount
    }
}

// MARK: - 数据源
extension JKNewFeatureViewController: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return maxCount
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        // 1.创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(newFeatureCellID, forIndexPath: indexPath) as! JKNewFeatureCell
        
        // 2.设置数据
        let imageName = imageNames[indexPath.item]
        cell.iconImageView.image = UIImage(named: imageName)
        
        // 不是最后一页就隐藏开始按钮
        if indexPath.item != (imageNames.count-1) {
            cell.startButton.hidden = true
        }
        
        // 3.返回
        return cell
    }
}

// MARK: - 代理
extension JKNewFeatureViewController: UICollectionViewDelegate {
    // cell完全显示的时候调用。注意传入的cell是上一个cell，不是当前显示的cell。indexPath也是一样
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    
        // 1.手动获取当前显示的cell对应的indexPath
        let index = collectionView.indexPathsForVisibleItems().last!
        // 2.根据获取的indexPath获取当前显示的cell
        let cell = collectionView.cellForItemAtIndexPath(index) as! JKNewFeatureCell
        
        pageControl.currentPage = index.item
        
        // 3.判断当前是否是最后一页
        if index.item == (imageNames.count - 1) {
            // 做动画
            cell.startAnimation()
        }
    }
}

// MARK: - 自定义cell
class JKNewFeatureCell: UICollectionViewCell {
    /** 新特性图片view */
    private lazy var iconImageView = UIImageView()
    /** 开始按钮 */
    private lazy var startButton: UIButton = {
        let btn = UIButton(imageName: nil, backgroundImageName: "new_feature_button")

        btn.addTarget(self, action: "startBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    //MARK: - 开始按钮点击
    @objc private func startBtnClick(){
        // 发出切换到主页的通知
        NSNotificationCenter.defaultCenter().postNotificationName(JKSwitchRootViewControllerNotification, object: nil, userInfo: [JKSwitchRootViewControllerKey : JKSwitchToMainValue])
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // 初始化
        setup()
    }
    
    //MARK: - 初始化
    private func setup(){
        // 1.添加子控件
        contentView.addSubview(iconImageView)
        contentView.addSubview(startButton)
        
        // 2.布局子控件，注意给谁做约束，就取消谁的自动约束
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        /* VF约束
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[iconImageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconImageView": iconImageView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[iconImageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconImageView": iconImageView])
        contentView.addConstraints(cons) */
        
        // SnapKit做新特性图片约束
        iconImageView.snp_makeConstraints { (make) -> Void in
            /*
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.bottom.equalTo(0)
            make.right.equalTo(0) */
            
            // 上面的可以一句话搞定
            make.edges.equalTo(0)
        }
        
        // SnapKit开始按钮约束
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-160)
        }
    }
    
    //MARK: - 开始按钮的动画
    func startAnimation(){
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        // 开发经验，按钮做动画的时候不能让它可以交互
        startButton.userInteractionEnabled = false
        /*
        第一个参数: 动画时间
        第二个参数: 延迟时间
        第三个参数: 震幅 0.0~1.0, 值越小震动越列害
        第四个参数: 加速度, 值越大震动越列害
        第五个参数: 动画附加属性
        第六个参数: 执行动画的block
        第七个参数: 执行完毕后回调的block
        */
        UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                self.startButton.userInteractionEnabled = true
        }
    }
}

// MARK: - 自定义布局
class JKNewFeatureViewLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        // 1.设置每个cell的尺寸
        itemSize = JKScreenBounds.size
        
        // 2.设置cell之间的间距
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        // 3.设置滚动方向
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 4.设置分页
        collectionView?.pagingEnabled = true
        
        // 5.禁用弹簧效果
        collectionView?.bounces = false
        
        // 6.去除滚动条
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}